
package com.xuelangyun.form.sys.service.impl;

import java.util.Arrays;

import com.xuelangyun.form.common.cache.annotation.TrCacheConfig;
import com.xuelangyun.form.common.cache.annotation.TrCacheEvictStrategy;
import com.xuelangyun.form.common.exception.DyformException;
import com.xuelangyun.form.common.service.CustomCacheServiceImpl;
import com.xuelangyun.form.common.utils.PageUtils;
import com.xuelangyun.form.common.utils.Query;
import com.xuelangyun.form.sys.dao.ISysConfigDao;
import com.xuelangyun.form.sys.entity.SysConfigEntity;
import com.xuelangyun.form.sys.service.ISysConfigService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

@Service
public class SysConfigServiceImplCustom extends CustomCacheServiceImpl<ISysConfigDao, SysConfigEntity> implements ISysConfigService {
		@Override
	public PageUtils queryPage(SysConfigEntity entity , PageUtils page) {
		String paramKey = entity.getParamKey();

		IPage<SysConfigEntity> ipage = this.page(
				new Query<SysConfigEntity>(page).getPage(),
				new QueryWrapper<SysConfigEntity>()
					.like(StringUtils.isNotBlank(paramKey),"param_key", paramKey)
					.eq("status", 1)
		);

		return new PageUtils(ipage);
	}
	
	 

	@Override
	@TrCacheEvictStrategy(value="#key",type= TrCacheEvictStrategy.EvictType.start)
	public void updateValueByKey(String key, String value) {
		
		SysConfigEntity config = new SysConfigEntity();
		config.setParamKey(key);
		config.setParamValue(value);
		
		updateById(config);
		 
	}

	@Override 
	@TrCacheEvictStrategy
	public void deleteBatch(String[] keys) {
		 
		this.removeByIds(Arrays.asList(keys));
	}

	@Override
	@TrCacheConfig(value="#key+ '.value'",cacheNull=true)
	public String getValue(String key) {
		SysConfigEntity config = getById(key);
		  
		return config == null ? null : config.getParamValue();
	}
	
	@Override
	@TrCacheConfig("#key + '.object'")
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return JSON.parseObject(value, clazz) ;// new Gson().fromJson(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new DyformException("获取参数失败");
		}
	}
}
